﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO;
using FolderSelect;



namespace PSPGenerator
{
    public partial class Synchronizer : Form
    {
        private string LoadPSPLocation { get { return System.Configuration.ConfigurationManager.AppSettings["LoadPSPLocation"].ToString().Trim(); } }
        private string SQLPlusLocation { get { return System.Configuration.ConfigurationManager.AppSettings["SQLPlusLocation"].ToString().Trim(); } }
        private string UserNamePassword { get { return System.Configuration.ConfigurationManager.AppSettings["UserNamePassword"].ToString(); } }
        private int CountCompile { get; set; }
        public Synchronizer()
        {
            InitializeComponent();
        }
        private string Directory{get;set;}

        private void button1_Click(object sender, EventArgs e)
        {
            var f = new FolderSelectDialog();
				f.Title = "Select files";
				f.InitialDirectory  = this.Directory = @"e:\projects\s004\plsql";
               
				if (f.ShowDialog(IntPtr.Zero))
				{
                
                 DirectoryInfo di = new DirectoryInfo(f.FileName);
                    
                foreach (var fi in di.GetFiles("*.sql"))
                {
                    AddNewFile(fi.FullName);
                }
                foreach (var fi in di.GetFiles("*.psp"))
                {
                    AddNewFile(fi.FullName);
                }
            }
            

        }

      

       

        private void btnFileUp_Click(object sender, EventArgs e)
        {
            if (lbFiles.SelectedIndices.Count == 0) return;
            var iStart = lbFiles.SelectedIndices[0];
            var iEnd = lbFiles.SelectedIndices[lbFiles.SelectedIndices.Count - 1];
            if (iStart == 0) return;
            var s = lbFiles.Items[iStart - 1];
            lbFiles.Items.RemoveAt(iStart - 1);
            lbFiles.Items.Insert(iEnd, s);
        }

        private void btnFileDown_Click(object sender, EventArgs e)
        {
            if (lbFiles.SelectedIndices.Count == 0) return;
            var iStart = lbFiles.SelectedIndices[0];
            var iEnd = lbFiles.SelectedIndices[lbFiles.SelectedIndices.Count - 1];
            if (lbFiles.Items.Count - 1 == iEnd) return;
             var s = lbFiles.Items[iEnd + 1];
            lbFiles.Items.RemoveAt(iEnd+1);
             lbFiles.Items.Insert(iStart, s);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog f = new SaveFileDialog();
            f.Filter = "Text File|*.txt";
            f.Title = "Save a text file";
            f.ShowDialog();

            using (StreamWriter file = new StreamWriter(f.FileName))
            {
                foreach(string line in lbFiles.Items){

                            file.WriteLine(line);
                }
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            lbFiles.Items.Clear();
        }

        private void btnLoadSetupFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFD = new OpenFileDialog();
            openFD.Filter = "text files (*.txt)|*.txt";
            openFD.FilterIndex = 1;
            openFD.RestoreDirectory = true;

            if (openFD.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    
                    string line;
                    StreamReader file = new StreamReader(openFD.FileName);
                    lbFiles.Items.Clear();
                    while ((line = file.ReadLine()) != null)
                    {
                        lbFiles.Items.Add(line);
                    }
                    file.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void AddNewFile(string filename) {
            bool IsFound = false;
            foreach (string item in lbFiles.Items) {
                if (item.ToLower() == filename.ToLower()) {
                    IsFound = true;
                    break;
                }
            }
            if (IsFound == false)
            {
                lbFiles.Items.Add(filename);
            }
        }



        private void lbFiles_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) {
                for (int i = lbFiles.SelectedIndices.Count - 1; i >= 0; i--)
                {
                    lbFiles.Items.RemoveAt(lbFiles.SelectedIndices[i]);
                }
                e.Handled = false;
            }
        }

    
        private string CompilePSP(string FileName)
        {
            string result = "";
            FileName=FileName.Replace("@", "");
            string ext = Path.GetExtension(FileName);
            if (ext == ".psp" || ext == ".sql")
            {
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.CreateNoWindow = true;

                if (ext == ".psp")
                {
                    p.StartInfo.FileName = this.LoadPSPLocation + "loadpsp.exe";
                    p.StartInfo.Arguments = string.Format("-replace -user {0} {1}", this.txtLogon.Text, FileName);
                }
                else
                {
                    p.StartInfo.FileName = this.SQLPlusLocation + "sqlplus.exe";
                    p.StartInfo.Arguments = string.Format("-S {0} @{1}", this.txtLogon.Text, FileName);
                }

                p.EnableRaisingEvents = true;
                p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(Compile_OutputDataReceived);
                p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(Compile_ErrorDataReceived);
                p.Exited += new EventHandler(Compile_Exited);
                p.Start();
                if (ext == ".sql") {
                    p.StandardInput.WriteLine("exit");
                }

                p.BeginErrorReadLine();
                p.BeginOutputReadLine();
                
                //p.Close();
            }
            return result;
        }
       
        void Compile_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            if (e.Data != null)
            {
                if (e.Data.Trim() != "")
                {
                    this.Invoke(new Function(delegate()
                    {
                        if (txtSuccessResult.Text.Trim() != "") txtSuccessResult.Text += "\r\n";
                        string[] args = ((System.Diagnostics.Process)sender).StartInfo.Arguments.Split('\\');
                        string filename = args[args.Length - 1];
                        txtSuccessResult.AppendText(filename + " - " + e.Data);
                    }));
                }
            }
        }

        void Compile_ErrorDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            if (e.Data != null)
            {
                if (e.Data.Trim() != "")
                {
                    this.Invoke(new Function(delegate()
                    {

                        if (txtFailedResult.Text.Trim() != "") txtFailedResult.Text += "\r\n";
                        string[] args = ((System.Diagnostics.Process)sender).StartInfo.Arguments.Split('\\');
                        string filename = args[args.Length - 1];
                        txtFailedResult.AppendText(filename + " - " + e.Data);
                        System.Media.SystemSounds.Exclamation.Play();
                    }));
                }
            }

        }
        void Compile_Exited(object sender, EventArgs e)
        {
            this.CountCompile += 1;
            if (this.CountCompile == this.lbFiles.Items.Count) {
                System.Media.SystemSounds.Beep.Play();
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            txtLogon.Text = this.UserNamePassword;
        }

        private void btnSync_Click(object sender, EventArgs e)
        {
            txtSuccessResult.Text = "Compiling...";
            txtFailedResult.Text = "";
            tabControl1.SelectTab(1);
            this.CountCompile = 0;
            foreach (string item in lbFiles.Items)
            {
                CompilePSP(item);

            }
        }

       
    }
}
